package main

import (

	"fmt"
	"time"
	"encoding/json"
	"crypto/rand"
	"math/big"
	"github.com/antonholmquist/jason"
	"net"
	"os"
	//"os/signal"
	"strconv"
)

func createReqJsonData( num int64) []string {

	var reqs = []string{ }
	for i:=0;i<int(num);i++{

		max := big.NewInt(1000)
		rand, _ := rand.Int(rand.Reader, max)
		reqs  = append( reqs,fmt.Sprintf( `{"token":"%s", "cmd":"socket.user_login","data":{ }}`  ,rand) )
	}
	return reqs
}


func asyncReqJson( datas []string ) []*SocketResponse {

	//ch := make( chan *SocketResponse )
	responses  := []*SocketResponse{}

	for _, data:= range datas {

		//fmt.Printf("Req %s \n", data)
		times, _ := strconv.ParseInt( os.Args[3], 10, 32)
		if len(os.Args) < 2 {
			fmt.Fprintf(os.Stderr, "Usage: %s host:port ", os.Args[0])
			os.Exit(1)
		}

		service := os.Args[1]
		tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
		checkError(err)
		//fmt.Println( " tcpAddr: ", tcpAddr )
		conn, err := net.DialTCP("tcp", nil, tcpAddr)
		defer conn.Close()
		checkError(err)
		go reqWithJson( conn, data, int(times) )
		time.Sleep(100 * time.Millisecond )

	}

	return responses
}


func reqWithJson(  conn *net.TCPConn , data string ,times int  ){

	_, err := conn.Write([]byte( data+"\n" ))
	checkError(err)
	var i int
	i = 0

	str :=`{ "cmd":"socket.getSession"}`
	d := json.NewDecoder(conn)
	for {

		var msg interface{}

		err := d.Decode(&msg)
		if  err != nil {
			conn.Close()
			fmt.Println( "d.Decode(&msg) ", err.Error()  )
			break
		}
		json_encode,err_encode := json.Marshal( msg )
		if err_encode!=nil {
			fmt.Println( "json.Marshal error:",err_encode.Error() )
			conn.Close()
			break
		}
		response_str := string( json_encode )

		fmt.Printf( " response: %s\n", response_str )
		msg_json, errjson := jason.NewObjectFromBytes( []byte(response_str) )
		checkError(errjson)
		cmd,  _ := msg_json.GetString("cmd")
		//fmt.Printf( " cmd: %s\n", cmd )

		if cmd=="socket.user_login"  {

			_,err = conn.Write([]byte(  str+"\n" ))
			checkError(err)

		}
		if cmd=="socket.getSession"  {
			_,err = conn.Write([]byte(  str+"\n" ))
			checkError(err)
			i++
			//time.Sleep(10 * time.Millisecond )
			if( i>=times ){
				conn.Close()
				fmt.Println( " i : ", i )
				fmt.Println( " conn close! " ,i )
				break
			}
		}
	}
	//conn.Close()

}
